﻿var mydata = {};
$('#searchForm').form().show();
$("#searchBtn").click(function(){
	getPerData(1);
});
$('input[name="isCheck"]').click(function(){
	getPerData(1);
});
/**
 * 查询函数
 */
var getPerData = function (page, rowNum, sortname, sortorder) {
    var queryParam = {};
    queryParam.checkState = "-1,2," + $('input[name="isCheck"]:checked').val();
    queryParam.planName = $("#searchForm #planName").val().trim();
	$.blockUI({message : "数据载入中,请稍候..."});
    $.ajax({
        url: webRoot+'index/gryApp.do',
        async : true,
        type : 'POST',
        data :queryParam
     }).done(function(serverData, textStatus, jqXHR) {
    	 mydata = eval("(" + jqXHR.responseText + ")");
    	 jQuery("#approval_jqGrid").jqGrid("reloadData",mydata);
//    	 if (data.totalRecords == 0 || $('input[name="isCheck"]:checked').val()!=2) $("#tb_approval_jqGrid").html("");
//		 var checkboxs = $('#approval_jqGrid .ui-jqgrid-bdiv input[type="checkbox"]:disabled');
//		 if (checkboxs.length == serverData.length) $("#tb_approval_jqGrid").html("");
         return mydata;
    }).fail(function() {fish.toast('error','查询失败，请稍后再试...');
    }).always(function() {
    	$.unblockUI();
    	});
    return mydata;
}
/**
 *
 */
var approval_opt = {
	    data: mydata,
	    datatype: "local",
	    height:'auto',
		colModel : [
		    {name : 'dmPlanId',label : '计划id',hidden : true
            }, {name : 'planName',label : '计划名称',width : 120
			}, {name : 'strategyGroupName',label : '策略组',width : 150,align : 'left',
				formatter : function(cellval, opts, rwdat, _act) {
					return '<label class="checkbox-inline" style="height:auto">'
						+ (rwdat.isCheck == 2 ?
								'<input type="checkbox" onclick="checkAll(this)" id="check'+rwdat.dmTaskId+'" value ="'+rwdat.dmTaskId+'" >' :
									'<input type="checkbox" onclick="checkAll(this)" disabled id="check" value ="'+rwdat.dmTaskId+'" >')
									+ cellval + '</label>';//
				}
			}, {name : 'strategyName',label : '策略名',width : 150,align : 'left'
			}, {name : 'dmTaskStageDtoList',label : '策略明细',width : 600,title : false,align : 'left',
				formatter : function(cellval, opts, rwdat, _act) {
					return StrategFormatter(cellval, opts, rwdat);
				}
			},{name : 'dmTaskId',label : '任务id',hidden : true
			}, {name : 'isCheck',label : '任务审批状态',hidden : true
			} ],
			toolbar: [true,"bottom"],
			userData : {
				strategyGroupName : '<label class="checkbox-inline">'
					+'<input type="checkbox" onclick="checkAll(this)" id="checkAll">批量选择</label>&nbsp;&nbsp;&nbsp;'
					+'<button type="button" class="btn btn-xs btn-success noPrivilege" onclick="batchsp(0,this)">批量通过</button>&nbsp;&nbsp;&nbsp;'
					+'<button type="button" class="btn btn-xs btn-danger noPrivilege" onclick="batchsp(1,this)">批量拒绝</button>',
			},
			rowNum : 5,
			rowList : [5,10,20],
			recordtext:'第{0}~{1}条/共{2}条',
			pgtext:'第{0}页/共{1}页',
			pginput: false,//是否显示输入框
//	    	viewrecords: false,//是否显示记录描述
			pager: true,
//			scrollOffset:0,
//			server: true,
		    jsonReader : {
	            root: "resultList",// json中代表实际模型数据的入口
	            page: "page",//当前页
	            total: "totalPages",// json中代表页码总数的数据
	            records: "totalRecords",//总记录数
	            repeatitems: false,// 如果设为false，则jqGrid在解析json时，会根据name来搜索对应的数据元素（即可以json中元素可以不按顺序）；而所使用的name是来自于colModel中的name设定。
	            cell: "cell",
	            id: "dmPlanId"
	        },
//		  pageData: getPerData ,//同步场景直接用getPerData,通过 jQuery("#jqGrid01").jqGrid("reloadData",getPerData(1));加载数据;异步场景用getPerData2
		  forceFit:true,  //当为ture时,调整列宽度不会改变表格的宽度
		  gridview : false,
			gridComplete : function() {//数据加载完成触发的事件
				var userdata = $("#approval_jqGrid").jqGrid("getGridParam","userData");
		        $("#tb_approval_jqGrid").html(userdata.strategyGroupName);
				crt($("#approval_jqGrid").find(".ui-jqgrid-btable")[0], [1,2]);
			}
};
$("#approval_jqGrid").jqGrid(approval_opt);
mydata = getPerData(1);
function isCheck(taskStage) {
	var isCheck = taskStage.isCheck;
	var json = JSON.stringify(taskStage).split(''),_json='';
	for(var i=0;i<json.length;i++){
		if(json[i]!=='"'){
			_json+=json[i];
		}
		else{
			_json+="'";
		}
	}
	if (isCheck == 0) {
		return '<span class="text-muted">审批理由：</span>'+taskStage.checkDesc;
	} else if (isCheck == 2) {
		return '<button type="button" class="btn btn-xs btn-success noPrivilege" onclick="sp(0,'+_json+',this)">通过</button>&nbsp;&nbsp;&nbsp;'
		+ '<button type="button" class="btn btn-xs btn-danger noPrivilege" onclick="sp(1,'+_json+',this)">拒绝</button>';
	} else if (isCheck == 1) {
		return '<span class="text-muted">审批理由：</span>'+taskStage.checkDesc;
	}
}
function StrategFormatter(cellval, opts, rwdat){
	var taskStage = rwdat.dmTaskStageDtoList;
	var tpl = '<div style="margin:0 -7px -1px -6px"><table cellspacing="0" cellpadding="0" border="0" width="100%">'
	for(var i=0; i<(taskStage.length >= 3 ? 3 : taskStage.length) ; i++){
		tpl += '<tr><td width="25%" id = "checkObjName"><span class="text-muted">表名:</span>'+taskStage[i].checkObjName+'</td>'
		tpl += '<td width="25%"><span class="text-muted">待归档数据:</span>'+taskStage[i].checkCount+'</td>'
		tpl += '<td width="25%"><span class="text-muted">总数据:</span>'+taskStage[i].totalRecordCount+'</td>'
		tpl += '<td style="width:106px;text-align:center">' + isCheck(taskStage[i])
		tpl += '</td></tr>';
	}
		tpl += '</table></div>'
	if(taskStage.length > 3){
		tpl += '<div class="showMore" style="margin:0 -7px -1px -6px;display:none"><table cellspacing="0" cellpadding="0" border="0" width="100%">'
		for(var i=3; i<taskStage.length; i++){
			tpl += '<tr><td width="25%" id = "checkObjName"><span class="text-muted">表名：</span>'+taskStage[i].checkObjName+'</td>'
			tpl += '<td width="25%"><span class="text-muted">待归档数据：</span>'+taskStage[i].checkCount+'</td>'
			tpl += '<td width="25%"><span class="text-muted">总数据：</span>'+taskStage[i].totalRecordCount+'</td>'
			tpl += '<td style="width:106px;text-align:center" >' + isCheck(taskStage[i])
			tpl += '</td></tr>';
		}
		tpl += '</table></div>'
		tpl += '<a class="show text-center" href="javascript:void(0);" onclick="showMore(this)"><span title="点击显示更多..." class="text-primary btn glyphicon glyphicon-option-horizontal" onclick=""></span>更多</a>'
	}
	return tpl;

}

function checkAll(target){ //全选复选框联动
	var id =$(target).attr('id');
	var checkboxs = $('#approval_jqGrid .ui-jqgrid-bdiv input[type="checkbox"]:not(:disabled)');
	if(id=='checkAll'){
			($(target).prop('checked') &&!$(target).prop('disabled')) ? $(checkboxs).prop('checked',true) : $(checkboxs).prop('checked',false);
	}else{
		for(var i=0; i<checkboxs.length;i++){
			if(!$(checkboxs[i]).prop('checked')){
				$('#checkAll').prop('checked',false);
				break;
			}else{
				$('#checkAll').prop('checked',true);
			}
		}
	}
}
/**
 * 批量审批
 * @param state	审批动作
 * @param tgt	this
 */
function batchsp(state, tgt) {
	var taskIdArr = [];
	var checkboxs = $('#approval_jqGrid .ui-jqgrid-bdiv input[type="checkbox"]:checked');
	for (var i = 0, j = checkboxs.length; i < j; i++) {
		taskIdArr[i] = $(checkboxs[i]).prop("value");
	}
	if (taskIdArr.length == 0) {fish.toast('warn','请选择一个策略组信息');}
	else {
		var tpl = '<div class="ui-dialog ui-dialogtree panel panel-default">'
			tpl += '<span class="close text-muted glyphicon glyphicon-remove"></span>'
			tpl += '<div class="panel-body">'
			tpl += '<form id="addForm" action="#" method="post" autocomplete="off" style="margin:0">'
			tpl += '<div class="text-left">'
			tpl += '<label>审批说明：</label>'
			tpl += '<div>'
			tpl += '<textarea class="form-control" rows="3" id = "checkDesc" placeholder = "请输入审核说明"></textarea>'
			tpl += '</div>'
			tpl += '</div>'
			tpl += '<div class="text-right" style="padding-top: 15px;">'
			tpl += '<button type="button" id="saveBtn" class = "btn-primary">&nbsp;确认&nbsp;</button>'
			tpl += '&nbsp;&nbsp;&nbsp;<button type="button" id="Cancel">&nbsp;取消</button>'
			tpl += '</div>'
			tpl += '</form>'
			tpl += '</div>'
			tpl += '</div>';
		var $dialog = $(tpl).appendTo('body');
		var $close = $dialog.find('.close');
		var $saveBtn = $dialog.find('#saveBtn');
		var $Cancel = $dialog.find('#Cancel');
		$dialog.dialog({canClose : false,show : true,width : 422,modal : true});
		$saveBtn.click(function() {
			var desc = $('#checkDesc').val();
			if (desc == null || desc == "") {
				return;
			}
			updateTask(taskIdArr, state, desc);
			$dialog.dialog('close').remove();
		});
		$Cancel.click(function() {
			$dialog.dialog('close').remove();
		});
		$close.click(function() {
			$dialog.dialog('close').remove();
		});

	}

}
/**
 * 单条记录审批
 * @param state	审批动作
 * @param taskStage	环节记录
 * @param tgt	this
 */

function sp(state,taskStage,tgt) {
	var tpl = '<div class="ui-dialog ui-dialogtree panel panel-default">'
		tpl += '<span class="close text-muted glyphicon glyphicon-remove"></span>'
		tpl += '<div class="panel-body">'
		tpl += '<form id="addForm" action="#" method="post" autocomplete="off" style="margin:0">'
		tpl += '<div class="text-left">'
		tpl += '<label>审批说明：</label>'
		tpl += '<div>'
		tpl += '<textarea class="form-control" rows="3" id = "checkDesc" placeholder = "请输入审核说明"></textarea>'
		tpl += '</div>'
		tpl += '</div>'
		tpl += '<div class="text-right" style="padding-top: 15px;">'
		tpl += '<button type="button" id="saveBtn" class = "btn-primary">&nbsp;确认&nbsp;</button>'
		tpl += '&nbsp;&nbsp;&nbsp;<button type="button" id="Cancel">&nbsp;取消</button>'
		tpl += '</div>'
		tpl += '</form>'
		tpl += '</div>'
		tpl += '</div>';
	var $dialog = $(tpl).appendTo('body');
	var $close = $dialog.find('.close');
	var $saveBtn = $dialog.find('#saveBtn');
	var $Cancel = $dialog.find('#Cancel');
	var $addForm = $dialog.find('#addForm');
	$dialog.dialog({
		canClose : false,
		show : true,
		width : 422,
		hide : true,
		modal : true
	});
	$saveBtn.click(function() {
		var desc = $('#checkDesc').val();
		taskStage.checkDesc = desc;
		if (desc == null || desc == "") {
			return;
		}
		if (state == 0) {
			taskStage.isCheck = 0;
		} else if (state == 1) {
			taskStage.isCheck = 1;
		}
		updateTaskStage(taskStage, state, tgt);
		$dialog.dialog('close').remove();
	});
	$Cancel.click(function() {
		$dialog.dialog('close').remove();
	});
	$close.click(function() {
		$dialog.dialog('close').remove();
	});
}
function showMore(target){
	var css = $(target).find('span').hasClass('glyphicon-option-horizontal') ? 'text-primary btn glyphicon glyphicon-option-vertical' : 'text-primary btn glyphicon glyphicon-option-horizontal';
		$(target).find('span').attr('class',css);
		$(target).prev('.showMore').toggle();
}
function crt(ts,cols){   //表格合并
    var rs = ts.rows;
    var up=0,sci=0,dci=0;
    var scv,dcv;
    var scs=new Array();
    for(var j=0;j<cols.length;j++){
        scv=null,up=0;
        for(var i=0;i<rs.length-1;i++){
            if(scs[i]==null) scs[i]=0;
            if(scs[i+1]==null) scs[i+1]=0;
            if(scv==null){
                sci=cols[j]-scs[i];
                scv=rs[i].cells[sci].innerText;
            }
            dci=cols[j]-scs[i+1];
            dcv=rs[i+1].cells[dci].innerText;
            if(scv==dcv&&dcv!=' '){
                scs[i+1]++;
                rs[i+1].deleteCell(dci);
                rs[i-up].cells[sci].rowSpan++;
                up++;
            }else{
                scv=null,up=0;
            }
        }
    }
}

var updateTaskStage = function (taskStage, state, tgt) {
    $.ajax({
        url: webRoot+'index/updateApp.do',
        async : true,
        type : 'POST',
        data : taskStage
     }).done(function(serverData, textStatus, jqXHR) {
    	 if (serverData[0] > 0) {//改环节--
			if (state == 0) {
    			$(tgt).parent().html('<span class="texta-sucess">审核通过</span>')
			} else if (state == 1) {
    			$(tgt).parent().html('<span class="texta-danger">审核不通过</span>')
			}
    	 }
    	 if (serverData[1] > 0) {//改策略组 --
    		 $('#approval_jqGrid .ui-jqgrid-bdiv #check'+taskStage.dmTaskId+'').prop("disabled",true);
    	 }
    	 fish.toast('success','审核成功');
    	 getPerData(1);//重载数据
        return false;
    }).fail(function() {
    }).always(function() {});
    return false;
};
var updateTask = function (taskIdArr, isCheck, desc) {
    $.ajax({
        url: webRoot+'index/updateTask.do',
        async : true,
        type : 'POST',
        traditional: true, //浅层序列化
        data : {"taskIdArr":taskIdArr,"isCheck":isCheck,"desc":desc}//JSON.stringify(...)
     }).done(function(serverData, textStatus, jqXHR) {
    	 fish.toast('success','审核成功');
    	 getPerData(1);//重载数据
        return false;
    }).fail(function() {
    }).always(function() {});
    return false;
};
